package com.jswlw.service.helper;

import com.jswlw.entity.biz.DistributionRecord;
import com.jswlw.entity.biz.Distributor;
import com.jswlw.entity.biz.OrderInfo;
import com.jswlw.service.biz.DistributionRecordService;
import com.jswlw.service.biz.DistributorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Component
public class DistributorHelper {

    @Autowired
    DistributorService distributorService;
    @Autowired
    DistributionRecordService recordService;

    public void deal(OrderInfo orderInfo) {
        //当前经销商
        Distributor distributor = distributorService.find4Id(orderInfo.getDistributorId());
        //处理分销规则
        if (distributor.getLevel().equals(2)) {
            Distributor distributor1 = distributorService.find4Id(distributor.getParentId());
            int level1 = orderInfo.getAmount() * (100 - distributor.getRate()) / 100;
            addRecord(orderInfo, distributor1, level1);
            int level2 = orderInfo.getAmount() - level1;
            addRecord(orderInfo, distributor, level2);
        }
        if (distributor.getLevel().equals(3)) {
            Distributor distributor2 = distributorService.find4Id(distributor.getParentId());
            Distributor distributor1 = distributorService.find4Id(distributor2.getParentId());
            int level1 = orderInfo.getAmount() * (100 - distributor2.getRate()) / 100;
            addRecord(orderInfo, distributor1, level1);
            int level2 = orderInfo.getAmount() - level1;
            int level3 = level2 * (100 - distributor.getRate()) / 100;
            addRecord(orderInfo, distributor, level3);
            level2 = level2 - level3;
            addRecord(orderInfo, distributor2, level2);
        }

    }

    private void addRecord(OrderInfo orderInfo, Distributor distributor, int amount) {
        DistributionRecord record = new DistributionRecord();
        record.setDistributorId(distributor.getId());
        record.setAmount(0);
        record.setCreateTime(new Date());
        record.setStatus(0);
        record.setUserId(orderInfo.getUserId());
        record.setOrderAmount(orderInfo.getAmount());
        record.setAmount(amount);
        record.setOrderSn(orderInfo.getSn());
        recordService.add(record);
    }
}
